package com.sz.biz.trade.ord.service.impl;

import com.sz.biz.trade.ord.entity.TrdOrder;
import com.sz.biz.trade.ord.entity.TrdOrderConfirmation;
import com.sz.biz.trade.ord.entity.TrdOrderStatus;
import com.sz.biz.common.AbstractVersionEntityService;
import com.sz.biz.trade.ord.service.TrdOrderConfirmationService;
import com.sz.biz.trade.ord.service.TrdOrderGoodsRelService;
import com.sz.biz.trade.ord.service.TrdOrderService;
import com.sz.biz.trade.ord.dto.PathPDFDto;
import com.sz.biz.trade.ord.dto.TrdOrderConfirmationInfoDto;
import com.sz.biz.trade.ord.dto.TrdOrderConfirmationSaveDto;
import com.sz.biz.trade.ord.dto.TrdOrderGoodsRelDto;
import com.sz.common.base.exception.Exceptions;
import com.sz.common.base.utils.JsonUtils;
import com.sz.common.base.utils.StringUtils;
import com.sz.biz.logistics.constants.ErrorCodes;
import com.sz.common.core.service.PrincipalUtils;
import com.sz.common.core.system.entity.SysFile;
import com.sz.common.core.system.service.SysFileService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * Function: 贸易订单服务<br>
 * Author: jifeixing <br>
 * Date: 2017-07-15 14:10:00
 */
@Service("trdOrderConfirmationService")
@Transactional(propagation = Propagation.REQUIRED, rollbackFor = Exception.class)
public class TrdOrderConfirmationServiceImpl extends AbstractVersionEntityService implements TrdOrderConfirmationService {

    @Autowired
    private TrdOrderGoodsRelService trdOrderGoodsRelService;

    @Autowired
    private TrdOrderService trdOrderService;

    @Autowired
    private SysFileService sysFileService;

    @Override
    protected String getMapperNamespace() {
        return "TrdOrderConfirmationMapper";
    }

    @Override
    public void save(TrdOrderConfirmationSaveDto trdOrderConfirmationSaveDto) {
        if(null == trdOrderConfirmationSaveDto || StringUtils.isEmpty(trdOrderConfirmationSaveDto.getOrderNo())){
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_ILLEGAL);
        }
        TrdOrder trdOrder =  trdOrderService.findFullInfoByOrderNo(trdOrderConfirmationSaveDto.getOrderNo());
        if(trdOrder== null){
            throw Exceptions.bizException(ErrorCodes.ERROR_COMMON,"不存在的订单号");
        }
        if (!trdOrderService.isNeedBuildPDF(trdOrder)) {
            throw Exceptions.bizException(ErrorCodes.ERROR_COMMON, "非SUNRUN订单，不能使用该方法");
        }
        TrdOrderConfirmationInfoDto trdOrderConfirmationInfoDto = findByOrderNo(trdOrderConfirmationSaveDto.getOrderNo());
        if(null != trdOrderConfirmationInfoDto){
            updateOrderConfirmation(trdOrderConfirmationSaveDto, trdOrderConfirmationInfoDto.getConfirmationNo());
        }else{
            saveOrderConfirmation(trdOrderConfirmationSaveDto, null);
        }
    }

    /**
     * 保存订单确认单
     * @param trdOrderConfirmationSaveDto
     * @param confirmationNo
     */
    private void saveOrderConfirmation(TrdOrderConfirmationSaveDto trdOrderConfirmationSaveDto, String confirmationNo){
        String jsonData = JsonUtils.toJSONString(trdOrderConfirmationSaveDto);
        TrdOrderConfirmation trdOrderConfirmation = new TrdOrderConfirmation();
        BeanUtils.copyProperties(trdOrderConfirmationSaveDto, trdOrderConfirmation);
        if(StringUtils.isEmpty(confirmationNo)){
            trdOrderConfirmation.setConfirmationNo(generateNewUid());
        }else{
            trdOrderConfirmation.setConfirmationNo(confirmationNo);
        }
        trdOrderConfirmation.setDealTime(trdOrderConfirmationSaveDto.getCreateTime());
        trdOrderConfirmation.setCreateUserId(PrincipalUtils.getAccountId());
        trdOrderConfirmation.setLastUpdateUserId(PrincipalUtils.getAccountId());
        trdOrderConfirmation.setJsonData(jsonData);
        dao.save(getSqlName("insertSelective"), trdOrderConfirmation);
        //回写业务单号到订单信息中
        String businessNo = trdOrderConfirmationSaveDto.getBusinessNo();
        if(!StringUtils.isEmpty(businessNo)){
            TrdOrder trdOrder = new TrdOrder();
            trdOrder.setOrderNo(trdOrderConfirmationSaveDto.getOrderNo());
            trdOrder.setBusinessNo(businessNo);
            trdOrderService.update(trdOrder);
        }
    }

    /**
     * 修改订单确认单
     * @param trdOrderConfirmationSaveDto
     * @param confirmationNo
     */
    private void updateOrderConfirmation(TrdOrderConfirmationSaveDto trdOrderConfirmationSaveDto, String confirmationNo){
        TrdOrderConfirmation trdOrderConfirmation = new TrdOrderConfirmation();
        BeanUtils.copyProperties(trdOrderConfirmationSaveDto, trdOrderConfirmation);
        trdOrderConfirmation.setIsDeleted(true);
        trdOrderConfirmation.setLastUpdateUserId(PrincipalUtils.getAccountId());
        dao.update(getSqlName("updateByPrimaryKeySelective"), trdOrderConfirmation);
        saveOrderConfirmation(trdOrderConfirmationSaveDto, confirmationNo);
    }
    /**
     * 订单确认单
     * @param orderNo
     * @return
     */
    @Override
    public TrdOrderConfirmationInfoDto findByOrderNo(String orderNo) {
        TrdOrderConfirmationInfoDto trdOrderConfirmationInfoDto = (TrdOrderConfirmationInfoDto) dao.findForObject(getSqlName("findByOrderNo"), orderNo);
        if(null != trdOrderConfirmationInfoDto){
            if(!StringUtils.isEmpty(trdOrderConfirmationInfoDto.getOrderStatus())){
                TrdOrderStatus trdOrderStatus = TrdOrderStatus.valueOfEnum(trdOrderConfirmationInfoDto.getOrderStatus());
                trdOrderConfirmationInfoDto.setOrderStatusName(trdOrderStatus.getName());
            }
            List<TrdOrderGoodsRelDto> trdOrderGoodsRels = trdOrderGoodsRelService.findByOrderNo(orderNo, 1);
            trdOrderConfirmationInfoDto.setOrderGoods(trdOrderGoodsRels);
        }
        return trdOrderConfirmationInfoDto;
    }

    /**
     * 订单确认单PDF导出路径
     * @param orderNo
     * @return
     */
    @Override
    public PathPDFDto findPathByOrderNo(String orderNo){
    	PathPDFDto pathPDFDto = (PathPDFDto) dao.findForObject(getSqlName("findPathByOrderNo"), orderNo);
    	if(pathPDFDto!=null){
            SysFile sysFile = sysFileService.getFileInfo(pathPDFDto.getFileId());
            if(sysFile!=null){
                pathPDFDto.setPath(sysFile.getFileLocation());
            }
        }
    	return pathPDFDto;
    }

    @Override
    public void createAndSavePDFFile(String orderNo){
        if(StringUtils.isEmpty(orderNo)){
            throw Exceptions.bizException(ErrorCodes.ERROR_ARGUMENT_EMPTY,"orderNo");
        }
        TrdOrderConfirmationInfoDto trdOrderConfirmationInfoDto = trdOrderService.getConfirmationByOrder(orderNo);
        if (trdOrderConfirmationInfoDto != null) {
            SysFile sysFile = trdOrderService.getPDFConfirmationByOrder(trdOrderConfirmationInfoDto);
            if (sysFile != null) {
                TrdOrderConfirmation upateFileInfoConfirmation = new TrdOrderConfirmation();
                upateFileInfoConfirmation.setOrderNo(orderNo);
                upateFileInfoConfirmation.setFileId(sysFile.getFileId());
                dao.update(getSqlName("updateFiledIdByOrderNo"), upateFileInfoConfirmation);
            }
        }
    }
}
